package controllers;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.io.FilenameUtils;

import utils.UserRoles;


import models.Location;
import models.SolutionAdoption;
import models.SolutionSubmission;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class AddAdoptSolutionServlet extends HttpServlet {
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();
 
	@SuppressWarnings("deprecation")
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try{
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String user_email = user.getEmail().toLowerCase();
        String User_Role_String = new UserRoles(user_email).toString();
        String strFile_Name = "";
        String strFile_Key = "";
        
        
		Date today = new java.util.Date();
		BlobKey blobKey = null;
		
		String sSolID = req.getParameter("txtsol_id");
		if ( sSolID == null ){
			resp.sendRedirect("/home.jsp?error=No solution id is null.");
		}
		Long lSolID = Long.parseLong(sSolID);
		if ( !SolutionConnect.doesRecordExists("solID", lSolID) ) {
			resp.sendRedirect("/home.jsp?error=No such solution exists.");
		}

		SolutionConnect SOL = new SolutionConnect();		
		List<HashMap<String,Object>> rs = SOL.getQuery("solID",lSolID);
		if ( rs == null )
			resp.sendRedirect("/home.jsp");		
		

		String	solTitle = (String) rs.get(0).get("Title");	
		String	solType	 = (String) rs.get(0).get("solType");
		String	solCode	 = (String) rs.get(0).get("solCode");

		Date dtImplemented = today;
        String _StrdtImplemented  = (String) req.getParameter("dtDate");
        if (_StrdtImplemented.length() > 0){
        	dtImplemented = new Date(_StrdtImplemented);	
        }
		
		SimpleDateFormat formatNowYear = new SimpleDateFormat("yyyy");
		SimpleDateFormat formatNowMonth = new SimpleDateFormat("MMMMM");
		String sYear = formatNowYear.format( dtImplemented );
		String sMonth = formatNowMonth.format(dtImplemented);
		
		boolean	_hasHardSavings; //NEWLY ADDED ON AUG 29 BY SYOUDEE FOR SEARCH PURPOSE
		boolean	_hasCostAvoidance; //NEWLY ADDED ON AUG 29 BY SYOUDEE FOR SEARCH PURPOSE
		boolean	_hasOppurtunityCost; //NEWLY ADDED ON AUG 29 BY SYOUDEE FOR SEARCH PURPOSE
		
		String	adptTeamLead = (String) req.getParameter("namSolTL");
		String	adptMembers = (String) req.getParameter("namSolTM");
		String	adptOthersMembers = (String) req.getParameter("namSolOtherTM");
		String	Customer = (String) req.getParameter("cmbCustomer");
		if ( Customer.indexOf("--") >= 0 ) Customer = "";
		
		String	sLocation = (String) req.getParameter("cmbSite");
		if ( sLocation.indexOf("--") >= 0 ) sLocation = "";
		
		//SEARCH FOR LOCATION in the LOCATION MODEL. -> ADDED BY SRVAN on sept 4
		String	LocationRegionName = "";
		String	LocationCode = "";
		Objectify ofy = ObjectifyService.begin();
		Query<Location> qq = ofy.query(Location.class).filter("LocationName", sLocation);
		for ( Location f : qq.fetch() ) {
			LocationRegionName = f.getLocationRegionName();
			LocationCode = f.getLocationCode();
			break;
		}
		
		String	processArea = (String) req.getParameter("cmbProcessarea");
		if ( processArea.indexOf("--") >= 0 ) processArea = "";
		
		BlobKey	adptTeamPicKey = null;
		
		
		
		String	easyRank = (String) req.getParameter("taRating");		
		int Rating = Integer.parseInt(easyRank);
		String	easyRankDesc = "";
		
		switch (Rating){
			case 1: easyRankDesc = "Difficult to implement"; break;
			case 2: easyRankDesc = "Somewhat easy to implement"; break;
			case 3: easyRankDesc = "Very easy to implement"; break;
		}
		
		String	achievedType = (String) req.getParameter("chkBenefits");
		int PrimaryBenefit = Integer.parseInt(achievedType);
		String achievedTypeDesc = "";
		switch (PrimaryBenefit){
				case 1: achievedTypeDesc = "Safety"; break;
				case 2: achievedTypeDesc = "Quality"; break;
				case 3: achievedTypeDesc = "Order Lead Time"; break;
				case 4: achievedTypeDesc = "Annual Production saving"; break;
				case 5: achievedTypeDesc = "Annual Material saving"; break;
				case 6: achievedTypeDesc = "Customer satisfaction"; break;
				case 7: achievedTypeDesc = "Employee engagement"; break;					
		}
		
		String	achievedValue = "";
		String	achievedUnits = "";
		
		if ( achievedTypeDesc.equalsIgnoreCase("Quality")) {
			
			achievedValue = (String) req.getParameter("taQuality");
			achievedUnits = (String) req.getParameter("cmbQualityOptions");
			
		}else if ( achievedTypeDesc.equalsIgnoreCase("Order Lead Time"))
		{
			achievedValue = (String) req.getParameter("taDays");
			achievedUnits = "In Days";
			
		}
		
		String _v1 = (req.getParameter("HardSavings") == "") ? "0" : req
				.getParameter("HardSavings");
		String _v2 = (req.getParameter("CostAvoid") == "") ? "0" : req
				.getParameter("CostAvoid");
		String _v3 = (req.getParameter("OpporCost") == "") ? "0" : req
				.getParameter("OpporCost");

		
		Float _hardSavings = new Float(0); // hardSavings
		Float _costAvoidance = new Float(0); // costAvoidance
		Float _oppurtunityCost = new Float(0); // oppurtunityCost
		
		if(_v1 != null && !_v1.equals("") ) _hardSavings = Float.parseFloat(_v1);// hardSavings
		if(_v2 != null && !_v2.equals("") ) _costAvoidance = Float.parseFloat(_v2);// costAvoidance
		if(_v3 != null && !_v3.equals("") ) _oppurtunityCost = Float.parseFloat(_v3);// oppurtunityCost
		Float _impDays = Float
				.parseFloat((req.getParameter("taImpTime") == "") ? "0" : req
						.getParameter("taImpTime"));// impDays	
		
		Float	hardSavings = _hardSavings;
		Float	costAvoidance = _costAvoidance;
		Float	oppurtunityCost = _oppurtunityCost;
		Float	annProdSavings = hardSavings + costAvoidance + oppurtunityCost;   
		Float	impDays = _impDays;
		_hasHardSavings = _hasCostAvoidance = _hasOppurtunityCost = false;
		
		if( _hardSavings > 0 ){
			_hasHardSavings=true;// hardSavings
		}

		if( _costAvoidance > 0 ){
			_hasCostAvoidance=true;// costAvoidance
		}
			
		if( _oppurtunityCost > 0 ){
			_hasOppurtunityCost=true;// oppurtunityCost
		}
		
		BlobKey	attachKey = null;
		String	Comment = (String) req.getParameter("tacomment");
		String	submittedBY = user_email;
		Date	submittedON = today;
		String	modifiedBY = user_email;
		Date	modifiedON = today;

        //EXTRACT THE FILE(S) FROM THE BLOB REQUEST
        Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
        if ( blobs != null)
        {
        	//TEAM PIC BLOB
        	blobKey = blobs.get("txtupload_teampic"); 
        	if ( blobKey != null )
        	{	 
        		final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);  
        		long size = blobInfo.getSize();            	
        		if(size > 0)
        		{
        			adptTeamPicKey = blobKey;
        		}else{
        			//NO BLOB SELECTED - delete unnamed blob
        			blobstoreService.delete(blobKey);
        		}
        	}
        	
        	blobKey = null;
        	
        	//ATTACHMENT PIC BLOB
        	blobKey = blobs.get("txtupload_attachment"); 
        	if ( blobKey != null )
        	{	 
        		final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);  
        		long size = blobInfo.getSize();            	
        		if(size > 0)
        		{
        			attachKey = blobKey;
        		}else{
        			//NO BLOB SELECTED - delete unnamed blob
        			blobstoreService.delete(blobKey);
        		}
        	}
        }    
		
		SolutionAdoption ADT = new SolutionAdoption();
		ADT.setSolID(lSolID);
		ADT.setSolCode(solCode); //NEW
		ADT.setSolTitle(solTitle);
		ADT.setSolType(solType);
		ADT.setDtImplemented(dtImplemented);
		ADT.setAdptTeamLead(adptTeamLead);
		ADT.setAdptMembers(adptMembers);
		ADT.setAdptOthersMembers(adptOthersMembers);
		ADT.setCustomer(Customer);
		ADT.setLocation(sLocation);
		ADT.setLocationCode(LocationCode); //NEW
		ADT.setLocationRegionName(LocationRegionName);
		ADT.setProcessArea(processArea);
		ADT.setAdptTeamPicKey(adptTeamPicKey);
		ADT.setEasyRank(easyRank);
		ADT.setEasyRankDesc(easyRankDesc);
		ADT.setAchievedType(achievedType);
		ADT.setAchievedTypeDesc(achievedTypeDesc);
		ADT.setAchievedValue(achievedValue);
		ADT.setAchievedUnits(achievedUnits);
		ADT.setHardSavings(hardSavings);
		ADT.setCostAvoidance(costAvoidance);
		ADT.setOppurtunityCost(oppurtunityCost);
		ADT.setAnnProdSavings(annProdSavings);				
		ADT.setHasHardSavings(_hasHardSavings);
		ADT.setHasCostAvoidance(_hasCostAvoidance);
		ADT.setHasOppurtunityCost(_hasOppurtunityCost);		
		ADT.setImpDays(impDays);
		ADT.setAttachKey(attachKey);
		ADT.setComment(Comment);
		ADT.setsYear(sYear);
		ADT.setsMonth(sMonth);
		ADT.setSubmittedBY(submittedBY);
		ADT.setSubmittedON(submittedON);
		ADT.setModifiedBY(modifiedBY);
		ADT.setModifiedON(modifiedON);
		
		ofy.put(ADT);
		
		//NEW CODE TO ADD SOLUTION CODE WITH REGION CODE
		Long adoptID = ADT.getAdoptID();
		String NewSiteCode = LocationCode + adoptID; 
		SolutionAdoption edititem = ofy.get(SolutionAdoption.class, adoptID);		
		edititem.setAdoptCode(NewSiteCode);
		ofy.put(edititem);
		
		
		UserActionsConnect.AddAction(user_email, "AddSolutionAdoptionServlet", "Inserted solID =" + ADT.getAdoptID(), "New SolutionAdoption, Blob Filename: " + strFile_Name, User_Role_String, today);
		resp.sendRedirect("/modules/default/display-adoption.jsp?adopt_id=" + ADT.getAdoptID());
		
	}catch(Exception ee){}
	}
} // Class End



/*
 * 
 * 		resp.setContentType("text/plain");

		 String parameter;
		 Enumeration parameterNames;
		 for( parameterNames = req.getParameterNames() ; parameterNames.hasMoreElements() ; ){
		     parameter = parameterNames.nextElement().toString();
		     resp.getWriter().println("[ "+parameter+" ] = "+req.getParameterValues(parameter)[0]+"<br/>");            
		}		

 * [ HardSavings ] = 01<br/>
[ UserProfileInfo ] = <br/>
[ txtProfileUNID ] = <br/>
[ Remote_User ] = Anonymous<br/>
[ FinanBenefits ] = 1<br/>
[ TotAnnualProd ] = 0<br/>
[ %%Surrogate_cmbQualityOptions ] = 1<br/>
[ taRating ] = 3<br/>
[ Path ] = <br/>
[ SolRequestor ] = Anonymous<br/>
[ dbName ] = global/collaboration/SavvySol.nsf<br/>
[ imgPath ] = global/collaboration/SavvySol.nsf<br/>
[ %%Surrogate_cmbSite ] = 1<br/>
[ %%Surrogate_cmbProcessarea ] = 1<br/>
[ Parentdocunid ] = 8AB00891A7FDDD4A4825766D002A23AF<br/>
[ FieldStatus ] = Draft<br/>
[ cmbCustomer ] = Diebold<br/>
[ txtUser ] = Anonymous<br/>
[ namSolTL ] = abduls@celestica.com<br/>
[ namSolTM ] = abdulsyed@celestica.com; ablajo@celestica.com; abryan@celestica.com<br/>
[ valFieldList ] = cmbCustomer,Customer,cmbProcessarea,Process Area,cmbSite,Location,dtDate,Implementation Date,namSolTL,Solution Team Lead,namSolTM,Team Members,taRating,Ease of implementation,chkBenefits,Check Benifits,taImpTime,Implementation Time<br/>
[ taQuality ] = 12<br/>
[ cmbSolSiteID ] = <br/>
[ lastnum ] = <br/>
[ %%Surrogate_FinanBenefits ] = 1<br/>
[ taDays ] = <br/>
[ namSolOtherTM ] = Team member<br/>
[ seqnum ] = Unassigned<br/>
[ Query_String ] = openform&~8AB00891A7FDDD4A4825766D002A23AF~<br/>
[ DocID ] = <br/>
[ %%Surrogate_cmbCustomer ] = 1<br/>
[ dtDate ] = 08/03/2012<br/>
[ QuickSearch ] = 0<br/>
[ cmbSite ] = Nashville<br/>
[ tacomment ] = <p>comment</p><br/>
[ CostAvoid ] = 23<br/>
[ %%Surrogate_chkBenefits ] = 1<br/>
[ %%Surrogate_taRating ] = 1<br/>
[ taImpTime ] = 123<br/>
[ photodocid ] = <br/>
[ $V2AttachmentOptions ] = 0<br/>
[ chkBenefits ] = 2<br/>
[ __Click ] = 852578AB003095E7.d91bd37116572efb85257609005f2620/$Body/0.6FE<br/>
[ cmbQualityOptions ] = DPU<br/>
[ HTTP_Referer ] = home.jsp<br/>
[ HTTP_Cookie ] = redirectto=/global/collaboration/SavvySol.nsf/frmsavvy%3FOpenForm%26login; LtpaToken=ZDKFFoPfuAGbPyVskMUDPgxWENdj6diTwzdqpeE75D7FBQstuBp54YMspDnQC9QK954X+DXijT/vWRAgUVFNx1YH5mHGt4jPCB0tifWosuGt2pgJbNa7IuYX37OM/SZM0a8uLCYmTmXAa3McMVWDrzC94QuiFJQFf2bJLqwT49kSa2czaPaL8+wPbTixFYVafkQicymLpty9Wg/82xzU4Ngnvk4yDky8FYgPnMPudwRgJMlD+7iu0JajQHyKgSlbe9VD5EwdP0vgocohqPS82xDEZeyv/GMv9nLoQglzfPOhPtAibxTgaxIqOoD/S0F0zShSxZAsawd38k99RwSuhuc2PO/nj4HCukoOIqhiwSNOwLVwWtrZEw==; DomAuthSessId=3B39AE311D8DFD103D6CDBD3A06EBFE5<br/>
[ OpporCost ] = 45<br/>
[ cmbSolRegion ] = <br/>
[ cmbProcessarea ] = Global Logistics and Trade Compliance<br/>
 * 
 * 
 * 
 */
